using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Domain.Entities;
using UniversalAdmin.Domain.Repositories;
using UniversalAdmin.Infrastructure.Data.Contexts;

namespace UniversalAdmin.Infrastructure.Repositories;

public class MenuRepository : Repository<Menu>, IMenuRepository
{
    public MenuRepository(ApplicationDbContext context) : base(context)
    {
    }

    public async Task<bool> HasChildrenAsync(Guid id)
    {
        return await _context.Menus.AnyAsync(m => m.ParentId == id);
    }

    public async Task<IEnumerable<Menu>> GetByIdsAsync(IEnumerable<Guid> ids)
    {
        return await _context.Menus
            .Where(m => ids.Contains(m.Id))
            .ToListAsync();
    }
}

public class MenuRoleRepository : Repository<MenuRole>, IMenuRoleRepository
{
    public MenuRoleRepository(ApplicationDbContext context) : base(context)
    {
    }

    public async Task<IEnumerable<Guid>> GetMenuIdsByRoleAsync(Guid roleId)
    {
        return await _context.MenuRoles
            .Where(mr => mr.RoleId == roleId)
            .Select(mr => mr.MenuId)
            .ToListAsync();
    }

    public async Task DeleteByRoleAsync(Guid roleId)
    {
        var menuRoles = await _context.MenuRoles
            .Where(mr => mr.RoleId == roleId)
            .ToListAsync();

        _context.MenuRoles.RemoveRange(menuRoles);
        await _context.SaveChangesAsync();
    }

    public new async Task AddRangeAsync(IEnumerable<MenuRole> menuRoles)
    {
        await _context.MenuRoles.AddRangeAsync(menuRoles);
        await _context.SaveChangesAsync();
    }
}